package com.itheima.reggie.common;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

/*
 * 自定义元数据对象处理器
 * */
@Component
@Slf4j
public class MyMetaObjecthandler implements MetaObjectHandler {

//

    /**
     * 插入操作,自动填充
     *
     * @author Mosetian
     * @date 2022-9-8 21:01
     * @param    metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {

        if (metaObject.hasSetter("createTime")) {
            metaObject.setValue("createTime", LocalDateTime.now());
        }
        if (metaObject.hasSetter("updateTime")) {
            metaObject.setValue("updateTime", LocalDateTime.now());
        }
        if (metaObject.hasSetter("createUser")) {
            metaObject.setValue("createUser", UserHolder.getUserId());
        }
        if (metaObject.hasSetter("updateUser")) {
            metaObject.setValue("updateUser", UserHolder.getUserId());
        }
    }

    /**
     * 更新操作,自动填充
     *
     * @author Mosetian
     * @date 2022-9-8 21:01
     * @param    metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        Long id = Thread.currentThread().getId();
        log.info("线程id为: {}", id);

        if (metaObject.hasSetter("updateTime")) {
            metaObject.setValue("updateTime", LocalDateTime.now());
        }
        if (metaObject.hasSetter("updateUser")) {
            metaObject.setValue("updateUser", UserHolder.getUserId());
        }
    }
}
